package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.CreateSceneResult;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SceneInterruptModeBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.manager.SceneOperateManager;
import com.qiantu.phone.ui.activity.AddConditionActivity;
import com.qiantu.phone.ui.activity.AddInterruptSceneActivity;
import com.qiantu.phone.ui.activity.EditSceneActivityNew;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.PanelBingingActivity;
import com.qiantu.phone.ui.activity.SceneAddGuideActivity;
import com.qiantu.phone.ui.adapter.RoomManagerSceneAdapter;
import com.qiantu.phone.ui.dialog.BottomInterruptSceneDialog;
import com.qiantu.phone.utils.SceneDetailUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class SceneListFragment extends AppFragment<AppActivity>{
    public static final int TYPE_SCENE_List = 1;
    public static final int TYPE_BING_LIST = 2;
    public static final int TYPE_INTERRUPT_LIST = 3;
    private RecyclerView sceneList;
    private LinearLayout ll_Noequipment;
    private TextView btn;
    private RoomManagerSceneAdapter sceneAdapter;

    private AppActivity mActivity;
    private int selectType;
    private int bingingType;
    private List<SceneInterruptModeBean.InterruptSceneBean> rules = new ArrayList<>();
    private SceneOperateManager mSceneOperateManager;
    private Handler mHandler;
    private ViewGroup sceneItemLongClickContainer;

    public void deleteAllScene(){
        List<String> serialNos = new ArrayList<>();
        for(SceneBean sceneBean : sceneAdapter.getAllSceneData()){
            serialNos.add(sceneBean.getSceneSerialNo());
        }
        LLHttpManager.deleteScene(this, serialNos, new HttpCallback<HttpData<Boolean>>(this){
            public void onSucceed(HttpData<Boolean> result) {
                super.onSucceed(result);
            }
        });
    }

    public SceneListFragment() {
    }

    public static SceneListFragment newInstance(int selectType) {
        SceneListFragment fragment = new SceneListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        fragment.selectType = selectType;
        return fragment;
    }

    public static SceneListFragment newInstance(int selectType,int bingingType) {
        SceneListFragment fragment = new SceneListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        fragment.selectType = selectType;
        fragment.bingingType = bingingType;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {}
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        sceneAdapter.cancelTimer();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scene_list;
    }

    @Override
    protected void initView() {
        sceneList = findViewById(R.id.scene_list);
        ll_Noequipment = findViewById(R.id.ll_Noequipment);
        btn = findViewById(R.id.btn);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        sceneList.setLayoutManager(gridLayoutManager);
        sceneAdapter = new RoomManagerSceneAdapter(getContext())
                .setSelectAct(false)
                .setShowFloorRoom(true)
                .setSingleSelect(isSingleSelect)
                .setBingingType(bingingType);
        sceneAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                SceneBean scene = sceneAdapter.getData().get(position);
                if(selectType == TYPE_BING_LIST){
                    PanelBingingActivity activity = (PanelBingingActivity) mActivity;
                    activity.showSceneOperateView(scene);
                }else if(selectType == TYPE_INTERRUPT_LIST){
                    AddInterruptSceneActivity activity = (AddInterruptSceneActivity) mActivity;
                    activity.showProtocolDialog(scene);
                }else{
                    if(mSceneOperateManager == null){
                        mSceneOperateManager = new SceneOperateManager(getContext());
                    }
                    mSceneOperateManager.setInterrupListener(new SceneOperateManager.InterruptListener() {
                        @Override
                        public void updateInterrupt(int time) {
                            sceneInterrupt(position,time);
                        }
                    });
                    mSceneOperateManager.onClick(itemView, scene.getSceneSerialNo());
                }
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.delete, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                SceneBean bean = sceneAdapter.getItem(position);
                sceneAdapter.removeSelected(bean.getSceneSerialNo());
                AddInterruptSceneActivity activity = (AddInterruptSceneActivity) mActivity;
                activity.removeSelect(bean.getSceneSerialNo());
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.btn_interrupt_cancel, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                cancelInterrupt(position);
            }
        });
        sceneAdapter.setOnItemLongClickListener(new BaseAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position) {
                scrollTo(position);

                if (mHandler == null) {
                    mHandler = new Handler();
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int[] outLocation = new int[2];
                        itemView.getLocationOnScreen(outLocation);
                        SceneBean scene =  sceneAdapter.getData().get(position);

                        ((HomeActivity) getActivity()).longClickSceneItem(outLocation[0], outLocation[1], itemView.getWidth(), itemView.getHeight(), scene, false);
                    }
                }, 50);

                return true;
            }
        });
        if(selectType == TYPE_BING_LIST) {
            sceneAdapter.setShowSettingButton(false);
        }else if(selectType == TYPE_INTERRUPT_LIST){
            sceneAdapter.setShowSettingButton(false);
        }
        sceneAdapter.setOnChildClickListener(R.id.setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                SceneDetailUtil.getSceneDetailAndToEdit(SceneListFragment.this, getAttachActivity(), sceneAdapter.getData().get(position).getSceneSerialNo());
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.btn_sort_scene_action,new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                PanelBingingActivity activity = (PanelBingingActivity) mActivity;
                activity.removeBingingData(sceneAdapter.getItem(position).getSceneSerialNo(),2);
                sceneAdapter.getItem(position).setTemporary(null);
                sceneAdapter.notifyItemChanged(position);
            }
        });
        sceneList.setAdapter(sceneAdapter);
    }
    @Override
    protected void initData() {
        List<SceneBean> scenes = LLSceneDBManager.getInstance(getContext()).getAll();
        if(selectType == TYPE_INTERRUPT_LIST){
            scenes = checkSceneData(scenes);
        }
        if(scenes == null || scenes.size() == 0){
            No_equipment();
        }else{
            Ye_sequipment();
            sceneAdapter.setTotalData(scenes);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        //没获取到数据才再刷新
//        if(sceneAdapter.getAllSceneData() == null || sceneAdapter.getAllSceneData().size() == 0){
        if(bingingType != 2){
            initData();
        }

//        }
    }

    public void scrollTo(int position) {
        if (sceneList != null) {
            sceneList.scrollToPosition(position);
//            ((HomeFragment)getParentFragment()).setAppBarLayoutOffset();
        }
    }

    private boolean isSingleSelect = false;
    public void setSingleSelect(boolean value) {
        isSingleSelect = value;
    }

    public void setTotalData(List<SceneBean> data){
        if(data == null){
            return;
        }
        if(sceneAdapter == null){
            return;
        }
        if(selectType == TYPE_INTERRUPT_LIST){
            data = checkSceneData(data);
        }
        sceneAdapter.setTotalData(data);
    }

    public void setActivity(AppActivity activity){
        mActivity = activity;
    }

    public void updateSceneData(SceneBean sceneBean){
        sceneAdapter.update(sceneBean);
    }

    private void No_equipment() {
        sceneList.setVisibility(View.GONE);
        ll_Noequipment.setVisibility(View.VISIBLE);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SceneAddGuideActivity.class);
            }
        });
    }

    //当前变化有设备
    private void Ye_sequipment() {
        sceneList.setVisibility(View.VISIBLE);
        ll_Noequipment.setVisibility(View.GONE);
    }

    private void gotoAddView(){
//        Intent intent = new Intent(getContext(), AddConditionActivity.class);
//        intent.putExtra("type", AddConditionActivity.TYPE_SCENE_LINKAGE);
//        startActivity(intent);
        startActivity(EditSceneActivityNew.class);
    }

    public void setSortData(String sceneSerialNo,int index){
        for(SceneBean sceneBean : sceneAdapter.getData()){
            if(sceneBean.getSceneSerialNo().equals(sceneSerialNo)){
                sceneBean.setTemporary(""+index);
                sceneAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    private List<SceneBean> checkSceneData(List<SceneBean> scenes){
        List<SceneBean> newScene = new ArrayList<>();
        for(int i = 0;i < scenes.size();i++){
            SceneBean sceneBean = scenes.get(i);
            List<SceneBean> subScenes = LLSceneDBManager.getInstance(getContext()).getScenesIntentBySerialNo(sceneBean.getSceneSerialNo());
            if(subScenes.size() != 0){
                Boolean isHave = false;
                for(int j = 0;j < rules.size();j++){
                    SceneInterruptModeBean.InterruptSceneBean bean = rules.get(j);
                    if(bean.getSceneSerialNo().equals(sceneBean.getSceneSerialNo())){
                        isHave = true;
                        break;
                    }
                }
                if(!isHave){
                    sceneBean.setTemporary(subScenes);
                    newScene.add(sceneBean);
                }
            }
        }
        return newScene;
    }

    public void addData(SceneBean sceneBean){
        sceneAdapter.addSelected(sceneBean);
    }

    public void setRules(List<SceneInterruptModeBean.InterruptSceneBean> rules){
        this.rules = rules;
    }

    public void sceneInterrupt(int position,int time){
        SceneBean sceneBean = sceneAdapter.getData().get(position);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis() + time*1000);
        sceneBean.setActionSettingExpireTime(format.format(date));
        LLSceneDBManager.getInstance(getContext()).updateExpireTime(sceneBean.getSceneSerialNo(),format.format(date));
        sceneAdapter.notifyDataSetChanged();
    }

    public void cancelInterrupt(int position){
        SceneBean sceneBean = sceneAdapter.getData().get(position);
        LLHttpManager.cancelInterrupMode(this, sceneBean.getSceneSerialNo(), new HttpCallback<HttpData<Void>>(this){
            public void onSucceed(HttpData<Void> result) {
                sceneBean.setActionSettingExpireTime("");
                LLSceneDBManager.getInstance(getContext()).updateExpireTime(sceneBean.getSceneSerialNo(),"");
                sceneAdapter.cancelTimer();
                sceneAdapter.notifyDataSetChanged();
            }
        });
    }
}
